import editForm from "../form.vue";
import { message } from "@/utils/message";
import {
  getAdAgentList,
  createAdAgent,
  updateAdAgent,
  deleteAdAgent
} from "@/api/ads";
import { transformI18n } from "@/plugins/i18n";
import { addDialog } from "@/components/ReDialog";
import { reactive, ref, onMounted, h } from "vue";
import type { AdAgentItem, PaginatedResponse } from "../utils/types";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { deviceDetection } from "@pureadmin/utils";
import type { PaginationProps } from "@pureadmin/table";
import { ElMessageBox } from "element-plus";
import { getPlatformInfo } from "./config";

export function useAdAgent() {
  const form = reactive({
    platform: "",
    name: "",
    keyword: ""
  });

  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const selectedRows = ref([]);

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 15,
    pageSizes: [15, 30, 50, 100],
    currentPage: 1,
    background: true
  });

  const columns: TableColumnList = [
    {
      type: "selection",
      width: 55,
      align: "left"
    },
    {
      label: "代理商名称",
      prop: "name",
      align: "left",
      minWidth: 200
    },
    {
      label: "平台",
      prop: "platform",
      width: 120,
      cellRenderer: ({ row }) => (
        <el-tag
          type={getPlatformInfo(row.platform, 'type')}
          effect="plain"
        >
          {getPlatformInfo(row.platform, 'label')}
        </el-tag>
      )
    },
    {
      label: "创建时间",
      prop: "created_at",
      minWidth: 160
    },
    {
      label: "更新时间",
      prop: "updated_at",
      minWidth: 160
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];

  function handleSelectionChange(val) {
    selectedRows.value = val;
  }

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    try {
      const params = {
        page: pagination.currentPage,
        size: pagination.pageSize,
        platform: form.platform,
        name: form.name,
        keyword: form.keyword
      };

      const { data } = await getAdAgentList(params);

      console.log("API响应:", data);

      // HTTP拦截器已经处理了错误情况，直接使用数据
      console.log("获取代理商数据成功");
      dataList.value = data.data || [];
      pagination.total = data.total || 0;
      pagination.currentPage = data.current_page || 1;
      pagination.pageSize = data.per_page || 15;
    } catch (error) {
      console.error("获取数据失败:", error);
      message("获取数据失败", { type: "error" });
    } finally {
      loading.value = false;
    }
  }

  function chores(curData: AdAgentItem, res: any, title: string, done?: (() => void)) {
    // HTTP拦截器已经处理了错误情况，能执行到这里说明成功了
    message(`您${title}了代理商 ${curData.name} 的数据`, {
      type: "success"
    });
    if (done) done(); // 关闭弹框
    onSearch(); // 刷新表格数据
  }

  function openDialog(title = "新增", row?: AdAgentItem) {
    addDialog({
      title: `${title}代理商`,
      props: {
        formInline: {
          id: row?.id,
          platform: row?.platform ? parseInt(row.platform.toString()) : 1,
          name: row?.name ?? ""
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as AdAgentItem;

        FormRef.validate(async (valid) => {
          if (valid) {
            try {
              let res;
              if (title === "新增") {
                res = await createAdAgent(curData);
              } else {
                res = await updateAdAgent(curData);
              }
              chores(curData, res, title, done);
            } catch (error) {
              message(`${title}失败`, { type: "error" });
            }
          }
        });
      }
    });
  }

  async function handleDelete(row?: AdAgentItem) {
    const ids = row ? [row.id] : selectedRows.value.map(item => item.id);
    const agentNames = row ? [row.name] : selectedRows.value.map(item => item.name);

    if (!ids.length) {
      message("请选择要删除的数据", { type: "warning" });
      return;
    }

    try {
      await ElMessageBox.confirm(
        `确认删除代理商：${agentNames.join("、")} 吗？\n注意：删除代理商后，关联的广告账号也会受到影响！`,
        "删除确认",
        {
          type: "warning"
        }
      );

      const res = await deleteAdAgent({ id: ids.join(",") });
      // HTTP拦截器已经处理了错误情况，能执行到这里说明成功了
      message(`成功删除${res.count || ids.length}个代理商`, { type: "success" });
      onSearch();
    } catch (error) {
      if (error !== "cancel") {
        message("删除失败", { type: "error" });
      }
    }
  }

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    selectedRows,
    onSearch,
    resetForm,
    openDialog,
    handleDelete,
    handleSelectionChange,
    handleSizeChange,
    handleCurrentChange
  };
}
